﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Coolzon.UI.Core
{
    /// <summary>
    /// 回复被动画修改掉的值，在组件再次被激活的时候，调用这些恢复值,
    /// 在Restore的时候，回将组件的IsRestore状态设置为ture，属性修改之后不会触发额外的事情发生
    /// </summary>
    public class PropertyValueKeeper
    {
        private List<Record> _records = new List<Record>();
        public static PropertyValueKeeper Instance = new PropertyValueKeeper();

        private PropertyValueKeeper()
        {

        }
        //public PropertyValueKeeper(Part instance)
        //{
        //    _instance = instance;
        //    _names = new List<DependencyProperty>();
        //    _values = new List<object>();
        //}

        public void Restore()
        {
            for(int index = 0; index<_records.Count;)
            {
                _records[index].Restore();
                _records.RemoveAt(index);
            }
        }

        public void Save(Widget instance, DependencyProperty name, object value)
        {
            foreach (Record record in _records)
            {
                if (record._instance == instance)
                {
                    record.Save(name, value);
                    return;
                }
            }

            Record newRecord = new Record(instance);
            newRecord.Save(name, value);
            _records.Add(newRecord);
        }

        public class Record
        {
            internal Widget _instance;

            private List<DependencyProperty> _names;
            private List<object> _values;
            public Record(Widget instance)
            {
                _names = new List<DependencyProperty>();
                _values = new List<object>();
                _instance = instance;
            }

            public void Save(DependencyProperty name, object value)
            {
                _names.Add(name);
                _values.Add(value);
            }

            public void Restore()
            {
                _instance.IsRestoring = true;
                for (int index = 0; index < _names.Count; )
                {
                    // 移除动画的锁定
                    _instance.BeginAnimation(_names[index], null);
                    _instance.SetValue(_names[index], _values[index]);
                    _names.RemoveAt(index);
                    _values.RemoveAt(index);
                }
                _instance.IsRestoring = false;
            }
        }
    }
}
